package com.gxuwz.medical.web.servlet.menu;

import java.io.IOException;
import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxuwz.medical.dao.MenuDao;
import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.domain.menu.Menu;
import com.gxuwz.medical.tools.ResponseUtil;
import com.gxuwz.medical.tools.StringUtil;

import net.sf.json.JSONObject;

public class MenuSaveServlet extends HttpServlet {

	DbUtil dbUtil = new DbUtil();
	MenuDao menuDao = new MenuDao();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		saveMenu(request, response);
	}

	private void saveMenu(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		Menu menu = null;
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String pid = request.getParameter("pid");
		String url = request.getParameter("url");
		System.out.println("id=" + id + "name=" + name + "pid=" + pid + "url=" + url);

		menu = new Menu(id, name, pid, url);
		Connection con = null;
		if (!StringUtil.isEmpty(id)) {
			menu.setId(id);

			try {
				JSONObject result = new JSONObject();
				// 查询ID是否存在
				con = dbUtil.getCon();
				response.setContentType("text/html;charset=utf-8");
				request.setCharacterEncoding("utf-8");
				MenuDao menuDao = new MenuDao();
				List<Menu> menu_tree_list = menuDao.findMenuById(menu);

				if (menu_tree_list.size() != 0) {

					System.out.println("菜单ID已存在，不可以添加！！");
					result.put("errorMsg", "true");
					result.put("errorMsg", "保存失败,菜单ID已存在，不可以添加！！");
				} else {
					System.out.println("可以添加！！");
					int saveNums = 0;
					if (!StringUtil.isEmpty(id)) {
						saveNums = menuDao.menuAdd(con, menu);
						System.out.print("增加菜单数量为" + saveNums);
					}
					if (saveNums > 0) {
						result.put("success", "true");
					} else {
						result.put("success", "true");
						result.put("errorMsg", "保存失败");
					}
				}
				ResponseUtil.write(response, result);
				// 用JSONArray返回数据
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					dbUtil.closeCon(con);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}

}
